// Copyright (c) 2025, yuxinyong and contributors
// For license information, please see license.txt
// Independent function to set the query for the shoe_part link field.
function set_shoe_part_query(frm) {
    frm.set_query('shoe_part', 'shoe_parts', function(doc, cdt, cdn) {
        // Get the value of the "style" link field on the main form.
        const style = frm.doc.style;

        // If no style is selected, return a filter that will show no results.
        if (!style) {
            return {
                filters: {
                    'name': 'No matching parts found.'
                }
            };
        }

        return {
            query: "zelin_shoe_biz.shoe_biz.doctype.shoe_style_variant.shoe_style_variant.get_style_shoe_parts",
            filters: {
                'style_name': style
            }
        };
    });
}

function handle_complete_shoe_parts_row_color(frm){
    // 确保子表存在
    if (frm.fields_dict['complete_shoe_parts'] && frm.fields_dict['complete_shoe_parts'].grid) {
        // 监听行渲染事件
        frm.fields_dict['complete_shoe_parts'].grid.wrapper.on('render', function() {
            // 获取所有行
            var rows = frm.fields_dict['complete_shoe_parts'].grid.grid_rows;
            
            // 遍历每一行
            rows.forEach(function(row) {
                // 获取override_type字段的值
                var overrideType = row.doc.override_type;
                
                // 如果值是Changed，设置背景色为黄色
                if (overrideType === 'Changed') {
                    $(row.row).css('background-color', 'yellow');
                } else {
                    // 如果不是Changed，恢复默认背景色
                    $(row.row).css('background-color', '');
                }
            });
        });
        
        // 初始渲染时也执行一次
        setTimeout(function() {
            var rows = frm.fields_dict['complete_shoe_parts'].grid.grid_rows;
            rows.forEach(function(row) {
                var overrideType = row.doc.override_type;
                if (overrideType === 'Changed') {
                    $(row.row).css('background-color', 'yellow');
                }
            });
        }, 100);
    }
}    

function reset_primary_button_for_complete_shoe_parts(frm) {
    if (!frm.doc.__islocal && frm.is_dirty()) {
        var unsaved = frm.doc.__unsaved || {};
        var onlyRelated = true;
        
        for (var key in unsaved) {
            if (key !== 'complete_shoe_parts' && !key.startsWith('complete_shoe_parts.')) {
                onlyRelated = false;
                break;
            }
        }
        
        if (onlyRelated) {
            frm.dirty(false);
            delete frm.doc.__unsaved;
            frm.toolbar.set_primary_action();
        }
    }
}

frappe.ui.form.on("Shoe Style Variant", {
    copy_field_to_quick_entry(frm){
	    let article_field = frm.get_docfield("shoe_parts", "article");
		article_field.get_route_options_for_new_doc = function(row) {		
            return {"item_group": "ARTICLE"}        
		}        
    },
    setup(frm) {
        frm.trigger("copy_field_to_quick_entry");
    },
    before_save: function(frm) {
        if (frm.doc.complete_shoe_parts && frm.doc.complete_shoe_parts.length > 0) {
            frm.doc.complete_shoe_parts = [];
        }
    },    
    onload(frm){
        if (!frm.doc.drawing_file) {
            frm.get_field("preview_html").$wrapper.html('');
        }
        reset_primary_button_for_complete_shoe_parts(frm);
    },
	refresh(frm) {
        handle_complete_shoe_parts_row_color(frm);
        reset_primary_button_for_complete_shoe_parts(frm);
        frm.trigger("copy_field_to_quick_entry");
        if (frm.doc.drawing_file) {
            frm.set_df_property("preview_html", "hidden", 0);
			zelin_shoe_biz.utils.preview_file(frm);
        } else {
            frm.get_field("preview_html").$wrapper.html('');
        }
        frm.set_query("article", "shoe_parts", function (doc, cdt, cdn) {
			const row = locals[cdt][cdn];
			return {
				query: "zelin_shoe_biz.queries.get_article",
				filters: {
					shoe_part: row.shoe_part,                    
				},
			};
		});        
        frm.set_query("item_code", "shoe_parts", function(doc, cdt, cdn) {
			const row = locals[cdt][cdn];
            let filters = {shoe_part: row.shoe_part}
            if (row.article){
                filters.article = row.article
            }
			return {
				query: "zelin_shoe_biz.queries.get_item_code",
				filters: filters
			};
        })
        if (frm.doc.grid_layout) {
            frappe.configure_columns.update_grid_columns(frm);
        }
        set_shoe_part_query(frm);
	},
    grid_layout: function(frm) {
        // This function will be called whenever the `grid_layout` link field changes.
        if (frm.doc.grid_layout) {
            frappe.configure_columns.update_grid_columns(frm);
        }
    }
});